package com.zch.book.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.sql.Date;
import java.util.List;

import com.zch.book.dao.BookDao;
import com.zch.book.entity.Book;
import com.zch.book.util.DBUtil;
import com.zch.book.util.DateFormat;

public class BookDaoImpl extends DBUtil implements BookDao {

	@Override
	public List<Book> getBookByPage(String sql, Object[] params) {
		List<Book> list = new ArrayList<Book>();
		executeQuery(sql, params);
		try {
			while(rs.next()){
				int bookNo = rs.getInt(1);//图书编号
				String bookName = rs.getString(2);//图书名字
				String bookAuthor = rs.getString(3);//图书作者
				Date bookDate = rs.getDate(4);//出版日期，读日期不用管日期类型
				String bookDescription = rs.getString(5);//图书描述
				Book book = new Book(bookNo, bookName, bookAuthor, bookDate, bookDescription);
				list.add(book);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeSource();
		}
		return list;
	}

	@Override
	public int getTotalCount(String sql, Object[] params) {
		int count = 0;
		executeQuery(sql, params);
		try {
			while(rs.next()){
				count = rs.getInt(1);//根据sql语句中的count(*)获得总记录数
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeSource();
		}
		return count;
	}

	@Override
	public Book getBookByBookNo(int bookNo) {
		Book book = null;
		String sql = "select * from book where bookno=?";
		Object[] params = new Object[]{bookNo};
		executeQuery(sql, params);
		try {
			while(rs.next()){
				String bookName = rs.getString(2);//图书名字
				String bookAuthor = rs.getString(3);//图书作者
				Date bookDate = rs.getDate(4);//出版日期，读日期不用管日期类型
				String bookDescription = rs.getString(5);//图书描述
				book = new Book(bookNo, bookName, bookAuthor, bookDate, bookDescription);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeSource();
		}
		return book;
	}

	@Override
	public boolean addBook(Book book) {
		String sql = "insert into book values(?,?,?,?,?)";
		Object[] params = new Object[]{book.getBookNo(),book.getBookName(),book.getBookAuthor(),
				book.getBookDate(),book.getBookDescription()};
		executeUpdate(sql, params);
		if(count > 0){
			return true;
		}
		return false;
	}

	@Override
	public boolean deleteBook(int bookNo) {
		String sql = "delete from book where bookno=?";
		Object[] params = new Object[]{bookNo};
		executeUpdate(sql, params);
		if(count > 0){
			return true;
		}
		return false;
	}

	@Override
	public boolean updateBook(Book book) {
		String sql = "update book set bookname=?,bookauthor=?,bookdate=?,bookdescription=? where bookno=?";
		Object[] params = new Object[]{book.getBookName(),book.getBookAuthor(),
			book.getBookDate(),book.getBookDescription(),book.getBookNo()};
		executeUpdate(sql, params);
		if(count > 0){
			return true;
		}
		return false;
	}

}
